package day4;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//利用反射创建对象
public class TestConstructor {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //1.获取类对象
        Class c=Class.forName("day4.Person");
        //第一种方式: 利用类对象的newInstance()直接创建
        //底层会调用无参构造方法...
        //Person p=(Person)c.newInstance();
        //System.out.println(p);
        //第二种方式: 利用Constructor的newInstance()来创建
        //好处可以设置私有权限  可以灵活的调用有参无参构造
        Constructor con1=c.getDeclaredConstructor();
        Constructor con2=c.getDeclaredConstructor(Integer.class);
        con1.setAccessible(true);//开启私有权限
        Person p1=(Person)con1.newInstance();
        Person p2=(Person)con2.newInstance(100);
        System.out.println(p1);
        System.out.println(p2);
    }
}
